import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import Company from 'src/entities/company.entity';
import { FindCompanyDto, CreatePhotoDto } from './company.dto';
import { isEmpty } from 'lodash';
import { ApiException } from 'src/core/exceptions/api.exception';
import Photo from 'src/entities/photo.entity';
import Industry from 'src/entities/industry.entity';
import Welfare from 'src/entities/welfare.entity';
import User from 'src/entities/user.entity';

@Injectable()
export class CompanyService {
  constructor(
    @InjectRepository(Company) private companyRepository: Repository<Company>,
    @InjectRepository(Photo) private photoRepository: Repository<Photo>,
    @InjectRepository(Industry) private industryRepository: Repository<Industry>,
    @InjectRepository(Welfare) private welfareRepository: Repository<Welfare>,
    @InjectRepository(User) private userRepository: Repository<User>,
  ) {}

  // 分页查询
  async find(query: FindCompanyDto) {
    const { page, size, name, jobFairsId } = query;

    const queryBuilder = this.companyRepository
      .createQueryBuilder('company')
      .leftJoinAndSelect('company.jobFairs', 'jobFairs')
      .select([
        'company.id',
        'company.name',
        'company.fullName',
        'company.industryId',
        'company.nature',
        'company.scale',
        'company.address',
        'company.createdAt',
        'jobFairs.id',
        'jobFairs.title',
      ])
      .orderBy('company.createdAt', 'DESC')
      .skip(size * (page - 1))
      .take(size);

    if (name !== undefined) {
      queryBuilder.andWhere('company.fullName LIKE :fullName', { fullName: `%${name}%` });
    }

    if (jobFairsId !== undefined) {
      queryBuilder.andWhere('jobFairs.id = :jobFairsId', { jobFairsId });
    }

    const [list, count] = await queryBuilder.getManyAndCount();
    return { list, count };
  }

  // 查询详细
  async findOne(id: number) {
    const company = await this.companyRepository
      .createQueryBuilder('company')
      .leftJoinAndSelect('company.photos', 'photo')
      .where('company.id = :id', { id })
      .select([
        'company.id',
        'company.userId',
        'company.logo',
        'company.name',
        'company.fullName',
        'company.industryId',
        'company.nature',
        'company.scale',
        'company.welfare',
        'company.workTime',
        'company.weekend',
        'company.workOvertime',
        'company.address',
        'company.introduce',
        'company.link',
        'photo.id',
        'photo.url',
      ])
      .getOne();

    if (isEmpty(company)) {
      throw new ApiException(10008);
    }

    // 获取行业名称
    const industry = await this.industryRepository.findOne({
      where: { id: company.industryId },
      select: ['name'],
    });

    // 获取福利信息
    const ids = company.welfare.split(',').map(Number);
    const welfare = await this.welfareRepository.find({
      where: { id: In(ids) },
      select: ['name', 'id'],
    });

    return {
      ...company,
      welfare,
      industryName: industry.name,
    };
  }

  // 更新公司信息
  async update(id: number, updateCompanyDto) {
    const company = await this.companyRepository.findOne({ where: { id } });
    if (isEmpty(company)) {
      throw new ApiException(10008);
    }
    const updateCompany = this.companyRepository.merge(company, updateCompanyDto);
    await this.companyRepository.save(updateCompany);
  }

  // 上传图片
  async uploadPhoto(createPhotosDto: CreatePhotoDto) {
    const { url, company_id } = createPhotosDto;
    const company = await this.companyRepository.findOne({ where: { id: company_id } });

    const photo = new Photo();
    photo.url = url;
    photo.company = company;
    const data = await this.photoRepository.save(photo);
    return { id: data.id, url: data.url };
  }

  // 移除图片
  async deletePhoto(id: number) {
    await this.photoRepository.delete(id);
  }
}
